/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: SignUpPresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.presenter;

import android.os.CountDownTimer;
import android.text.TextUtils;
import android.widget.CheckBox;

import io.bhex.app.BuildConfig;
import io.bhex.app.R;
import io.bhex.app.account.bean.VerifyCodeBean;
import io.bhex.app.base.AppUI;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.app.utils.RegexUtils;
import io.bhex.app.view.InputView;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BasePresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.exception.NetException;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.UISafeKeeper;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.account.AccountInfoApi;
import io.bhex.sdk.account.LoginApi;
import io.bhex.sdk.account.bean.OrderParamResponse;
import io.bhex.sdk.account.bean.RegisterRequestBean;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.sdk.account.bean.VerifyFirstRequest;
import io.bhex.sdk.config.ConfigApi;
import io.bhex.sdk.config.bean.IndexConfigBean;

/**
 * 描   述：注册
 * ================================================
 */

public class SignUpPresenter extends BasePresenter<SignUpPresenter.SignUpUI> {

    private VerifyCodeBean currentEmailVerifyCode;
    private VerifyCodeBean currentMobileVerifyCode;
    //验证码
    private String orderIdOfEmail="";
    private String orderIdOfMobile="";

//    private boolean isStartTimer=false;//标识timer是否开启

    public interface SignUpUI extends AppUI{


        void registerSuccess();

        void registerFailed(String msg);

        void hideKeyboard();

        void setAuthTv(String s);

        void setAuthTvStatus(boolean b);

        boolean isChinaMobile();

        void showProtocolUrls(IndexConfigBean response);
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, SignUpUI ui) {
        super.onUIReady(activity, ui);
    }

    @Override
    public void onResume() {
        super.onResume();
        getProtocolUrls();
    }

    /**
     * 获取协议地址
     */
    private void getProtocolUrls() {
        ConfigApi.getIndexConfig(new SimpleResponseListener<IndexConfigBean>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(IndexConfigBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    getUI().showProtocolUrls(response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 切换注册方式
     * @param defulat_signup_email
     */
    public void switchSignupWay(boolean defulat_signup_email) {
        if (timer != null) {
            timer.cancel();
        }
        getUI().setAuthTv(getString(R.string.string_get_auth_code));
        getUI().setAuthTvStatus(true);

    }

    /**
     * 校验账号
     * @param isEmail
     * @param accountV
     * @return
     */
    public boolean checkAccount(boolean isEmail,InputView accountV) {
        final String account = accountV.getInputString();
        if (TextUtils.isEmpty(account)) {
            if (isEmail) {
                accountV.setError(getResources().getString(R.string.input_email));

            }else{
                accountV.setError(getResources().getString(R.string.input_phone_number));
            }
            return false;
        }else{
            accountV.setError("");
        }
        return true;
    }

    /**
     * 校验密码
     * @param pwdV
     * @param pwd2V
     * @return
     */
    public boolean checkPasswd(InputView pwdV, InputView pwd2V) {
        String pwd = pwdV.getInputString();
        if (TextUtils.isEmpty(pwd)) {
            pwdV.setError(getResources().getString(R.string.input_pwd));
            return false;
        }else{
            pwdV.setError("");
        }

        if (!RegexUtils.checkPasswd(pwd)) {
            pwdV.setError(getResources().getString(R.string.input_pwd_reg_no_match));
            return false;
        }else{
            pwdV.setError("");
        }

        String pwd2 = pwd2V.getInputString();
        if (TextUtils.isEmpty(pwd2)) {
            pwd2V.setError(getResources().getString(R.string.input_pwd2));
            return false;
        }else{
            pwd2V.setError("");
        }
        if (!pwd.equals(pwd2)) {
            pwd2V.setError(getString(R.string.string_pwd_no_match));
            return false;
        }else{
            pwd2V.setError("");
        }
        return true;
    }

    /**
     * 校验内容的合法性
     */
    public boolean checkInputContentLegality(boolean isEmail, String mobileCode, InputView accountV, InputView pwdV, InputView pwd2V, InputView verifyCodeV, CheckBox protocolCheckbox) {
        final String account = accountV.getInputString();
        if (TextUtils.isEmpty(account)) {
            if (isEmail) {
                accountV.setError(getResources().getString(R.string.input_email));

            }else{
                accountV.setError(getResources().getString(R.string.input_phone_number));
            }
            return false;
        }else{
            accountV.setError("");
        }

        if (isEmail) {
            //邮箱校验
//            if (!RegexUtils.checkEmail(account)) {
//                accountV.setError(getResources().getString(R.string.input_right_email_please));
//                return false;
//            }else{
//                accountV.setError("");
//            }
        }else{
            //手机号校验
            //TODO 暂时不做格式校验
//            if (mobileCode.equals("+86")) {
//                if (!RegexUtils.checkMobile(account)) {
//                    accountV.setError(getResources().getString(R.string.input_right_mobile_please));
//                    return false;
//                }else{
//                    accountV.setError("");
//                }
//            }
        }


        String pwd = pwdV.getInputString();
        if (TextUtils.isEmpty(pwd)) {
            pwdV.setError(getResources().getString(R.string.input_pwd));
            return false;
        }else{
            pwdV.setError("");
        }

        if (!RegexUtils.checkPasswd(pwd)) {
            pwdV.setError(getResources().getString(R.string.input_pwd_reg_no_match));
            return false;
        }else{
            pwdV.setError("");
        }

        String pwd2 = pwd2V.getInputString();
        if (TextUtils.isEmpty(pwd2)) {
            pwd2V.setError(getResources().getString(R.string.input_pwd2));
            return false;
        }else{
            pwd2V.setError("");
        }

        if (!pwd.equals(pwd2)) {
            pwd2V.setError(getString(R.string.string_pwd_no_match));
            return false;
        }else{
            pwd2V.setError("");
        }

        String verifyCode = verifyCodeV.getInputString();
        if (TextUtils.isEmpty(verifyCode)) {
            verifyCodeV.setError(getResources().getString(R.string.input_verify));
            return false;
        }else{
            verifyCodeV.setError("");
        }

        //校验验证码
        if (isEmail) {
            if(TextUtils.isEmpty(orderIdOfEmail)) {
                verifyCodeV.setError(getString(R.string.string_verify_code_invalid));
                return false;
            }
        }else{
            if(TextUtils.isEmpty(orderIdOfMobile)) {
                verifyCodeV.setError(getString(R.string.string_verify_code_invalid));
                return false;
            }
        }

//        if (isEmail) {
//            if (currentEmailVerifyCode == null) {
//                verifyCodeV.setError(getString(R.string.string_verify_code_invalid));
//                return false;
//            }
//            orderId = currentEmailVerifyCode.getOrderId();
//            if (TextUtils.isEmpty(orderId)) {
//                verifyCodeV.setError(getString(R.string.string_verify_code_invalid));
//                return false;
//            }
//        }else{
//            if (currentMobileVerifyCode == null) {
//                verifyCodeV.setError(getString(R.string.string_verify_code_invalid));
//                return false;
//            }
//            orderId = currentMobileVerifyCode.getOrderId();
//            if (TextUtils.isEmpty(orderId)) {
//                verifyCodeV.setError(getString(R.string.string_verify_code_invalid));
//                return false;
//            }
//        }
        verifyCodeV.setError("");

        if (!protocolCheckbox.isChecked()) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_must_agree_registe_protocol));
            return false;
        }
        return true;
    }

    /**
     * 校验内容的合法性
     */
    public boolean checkInputContentIsEmpty(boolean isEmail, String mobileCode, InputView accountV, InputView pwdV, InputView pwd2V, InputView verifyCodeV, CheckBox protocolCheckbox) {
        final String account = accountV.getInputString();
        if (TextUtils.isEmpty(account)) {
            return false;
        }

        String pwd = pwdV.getInputString();
        if (TextUtils.isEmpty(pwd)) {
            return false;
        }

        String pwd2 = pwd2V.getInputString();
        if (TextUtils.isEmpty(pwd2)) {
            return false;
        }

        String verifyCode = verifyCodeV.getInputString();
        return !TextUtils.isEmpty(verifyCode);
    }

    /**
     *
     * 注册
     *
     * */
    public void signUp(final boolean isEmail, String mobileCode, InputView accountV, InputView pwdV, InputView pwd2V, InputView verifyCodeV, InputView inviteCodeV, CheckBox protocolCheckbox) {
        if (!NetWorkStatus.isConnected(getActivity())) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            return;
        }
        if (!checkInputContentLegality(isEmail,mobileCode,accountV,pwdV,pwd2V,verifyCodeV,protocolCheckbox)) {
            return;
        }
        final String account = accountV.getInputString();
        String pwd = pwdV.getInputString();
        String pwd2 = pwd2V.getInputString();
        String verifyCode = verifyCodeV.getInputString();


        String inviteCode = inviteCodeV.getInputString();

        boolean bNet = NetWorkStatus.isConnected(getActivity());
        if (!bNet) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            return;
        }

        getUI().hideKeyboard();

        RegisterRequestBean bean = new RegisterRequestBean();
        bean.isEmail = isEmail;
        bean.account = account;
        bean.password1 = pwd;
        bean.password2 = pwd2;
        bean.invite_code = inviteCode;
        bean.verify_code = verifyCode;
        if (isEmail) {
            bean.order_id = orderIdOfEmail;
        }else{
            bean.order_id = orderIdOfMobile;
            bean.mobileCode = mobileCode;
        }

        LoginApi.RequestSignUp(CommonUtil.getChannel(getActivity()),bean, UISafeKeeper.guard(getUI(), new SimpleResponseListener<UserInfoBean>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("",getResources().getString(R.string.string_loading_hint_text));
            }

            @Override
            public void onSuccess(UserInfoBean data) {
                super.onSuccess(data);

                if (CodeUtils.isSuccess(data,true)) {

                    ToastUtils.showShort(getActivity(), getResources().getString(R.string.string_signup_success));

                    boolean fingerOpen = SPEx.isFingerOpen();
                    if (fingerOpen){
                        SPEx.setFingerAuth(true);
                        AppData.HOME_LOCKED=false;
                        AppData.isHome=false;
                    }

                    getUI().registerSuccess();
                }
                /*else{
                    getUI().registerFailed(data.getMsg());
                }*/
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
//                if (error instanceof NetException) {
//                    NetException nt = (NetException)error;
//                    ToastUtils.showShort(getActivity(),nt.getCode()+":"+nt.getShowMessage());
//                }else{
//
//                    ToastUtils.showShort(getActivity(),getResources().getString(R.string.server_error));
//                }
            }
        }));
    }

    public void verifyFirstRequest(final boolean isEmail, String mobileCode, InputView accountView, String token){
        if (!NetWorkStatus.isConnected(getActivity())) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            return;
        }
        final String account = accountView.getInputString();
        if (TextUtils.isEmpty(account)) {
            accountView.setError(isEmail?getResources().getString(R.string.input_email):getResources().getString(R.string.input_phone_number));
            return;
        }else{
            accountView.setError("");
        }
        if (isEmail) {
            //手机号校验
//            if (!RegexUtils.checkEmail(account)) {
//                accountView.setError(getResources().getString(R.string.input_right_email_please));
//                return;
//            }else{
//                accountView.setError("");
//            }
        }else{
//            if (!RegexUtils.checkMobile(account)&&!getUI().isChinaMobile()){
//                accountView.setError(getResources().getString(R.string.input_right_mobile_please));
//                return;
//            }else{
//                accountView.setError("");
//            }
        }

        final VerifyFirstRequest requestData = new VerifyFirstRequest();
        requestData.bEmail = isEmail;
        requestData.account = account;
        requestData.token = token;
        requestData.captcha_id = BuildConfig.DEEPKNOW_ID;
        if (isEmail) {
        }else{
            requestData.mobileCode = mobileCode;
        }
        AccountInfoApi.RequestVerifyFirstForSignUp(requestData, UISafeKeeper.guard(getUI(), new SimpleResponseListener<OrderParamResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("",getString(R.string.string_loading_hint_text));
            }

            @Override
            public void onSuccess(OrderParamResponse data) {
                super.onSuccess(data);

                if (CodeUtils.isSuccess(data,true)) {
                    if (isEmail) {
                        orderIdOfEmail = data.getOrderId();
                    }else{
                        orderIdOfMobile = data.getOrderId();
                    }
                    getUI().setAuthTvStatus(false);
                    timer.start();
                }

            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (error instanceof NetException) {
                    NetException nt = (NetException)error;
//                    ToastUtils.showShort(getActivity(),nt.getCode()+":"+nt.getShowMessage());
                }else{

//                    ToastUtils.showShort(getActivity(),getResources().getString(R.string.server_error));
                }
            }
        }));
    }

    /**
     * 倒计时
     */
    private CountDownTimer timer = new CountDownTimer(AppData.DOWN_TIME_CODE, AppData.DOWN_TIME_INTERVAL_CODE) {
        @Override
        public void onTick(long millisUntilFinished) {
            getUI().setAuthTv((millisUntilFinished / 1000)
                    + getActivity().getResources().getString(
                    R.string.after_second));
        }

        @Override
        public void onFinish() {
            getUI().setAuthTvStatus(true);
            getUI().setAuthTv(getResources().getString(
                    R.string.string_get_auth_code));
        }
    };

}
